package com.feihong.yw189.activity.kuandai;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.tiaoxingma.TiaoXingMaActivity;
import com.feihong.yw189.adapter.Kuandai.ChooseSimAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.Kaika.ChooseSimModel;
import com.holenzhou.pullrecyclerview.BaseRecyclerAdapter;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 手机号码
 */

public class ChooseSimKaActivity extends BaseActivity {

    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.et_input)
    EditText minput;
    @BindView(R.id.iv_search)
    ImageView imageView;

    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;
    private int page = 1;
    List<ChooseSimModel.DataBean.ListBean> mlisbean;
    ChooseSimAdapter mAdapter;
    private String title;
    final int page_size = 10;
    private HashMap<String, String> mSimMap;

    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataLayoutTv;

    public static final String SELECT_SIM_NUM_KEY = "SELECT_SIM_NUM_KEY";
    public static final String SELECT_SIM_NUM_ID_KEY = "SELECT_SIM_NUM_ID_KEY";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listchoose);
        ButterKnife.bind(this);

        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initView() {
        mNullDataLayout.setVisibility(View.GONE);
        mNullDataLayoutTv.setText("暂无对应条件的ICCID号码信息");
        txtPagetitle.setText("ICCID号");
        ivLin.setImageResource(R.mipmap.img_saoma);
        ivLin.setBackgroundColor(Color.TRANSPARENT);
        minput.setHint("模糊搜索");
        minput.setInputType(InputType.TYPE_CLASS_NUMBER);
        title = minput.getText().toString().trim();
        mlisbean = new ArrayList<>();
        // 初始化PullRecyclerView
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mAdapter = new ChooseSimAdapter(this, R.layout.item_choosesim, mlisbean);
        mPullRecyclerView.setAdapter(mAdapter);

        mSimMap = new HashMap<String, String>();
        final Intent intent = getIntent();
        ArrayList<String> arrayList = intent.getStringArrayListExtra("simList");
        if (arrayList != null) {
            for (String simNum : arrayList) {
                mSimMap.put(simNum, simNum);
            }
        }
        final String pption = intent.getStringExtra("position");
        // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.setColorSchemeResources(R.color.appBlue);
        // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.enablePullRefresh(true);
        // 开启数据全部加载完成时的底部提示，默认为false
        mPullRecyclerView.enableLoadMore(false);
        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {

                mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
                page = 1;
                queryData();
            }

            @Override
            public void onLoadMore() {

                mPullRecyclerView.enableLoadDoneTip(true, R.string.load_done_tip);
                queryData();
            }
        });
        mPullRecyclerView.postRefreshing();
        mAdapter.setOnRecyclerItemClickListener(new BaseRecyclerAdapter.OnRecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mSimMap != null && mSimMap.containsKey(mlisbean.get(position).getIccid_no())) {
                    showToast("此号码已选择，请选择其他号码");
                } else {
                    if (!TextUtils.isEmpty(pption)) {
                        Intent intentPhone = new Intent();
                        intentPhone.putExtra(SELECT_SIM_NUM_KEY, mlisbean.get(position).getIccid_no());
                        intentPhone.putExtra(SELECT_SIM_NUM_ID_KEY, mlisbean.get(position).getId());
                        setResult(RESULT_OK, intentPhone);
                        finish();
                    } else {
                        Intent intentPhone = new Intent();
                        intentPhone.putExtra(SELECT_SIM_NUM_KEY, mlisbean.get(position).getIccid_no());
                        intentPhone.putExtra(SELECT_SIM_NUM_ID_KEY, mlisbean.get(position).getId());
                        setResult(RESULT_OK, intentPhone);
                        finish();
                    }
                }
            }
        });


    }

    public void bindData() {
    }

    private void queryData() {
        title = minput.getText().toString().trim();
        App.getApp().getHttpTools().getSim(title, page, page_size, CallBackUp);
    }

    @OnClick({R.id.rl_goback, R.id.iv_search, R.id.iv_lin, R.id.requery_data_tv})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_lin:
                Intent intent = new Intent(getActivity(), TiaoXingMaActivity.class);
                startActivityForResult(intent, TiaoXingMaActivity.REQ_CODE);
                break;
            case R.id.rl_goback:
                finish();
                break;
            case R.id.iv_search:
                title = minput.getText().toString().trim();

                if (!TextUtils.isEmpty(title)) {
                    if (mPullRecyclerView.getVisibility() == View.GONE) {
                        mNullDataLayout.setVisibility(View.GONE);
                        mConnectNetErrorLayout.setVisibility(View.GONE);
                    }
                    page = 1;
                    //initView();
                    mPullRecyclerView.postRefreshing();
                } else {
                    showToast("请输入搜索内容");
                }
                break;
            case R.id.requery_data_tv:
                mConnectNetErrorLayout.setVisibility(View.GONE);
                queryData();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case TiaoXingMaActivity.REQ_CODE:
                    String iccid = data.getStringExtra(TiaoXingMaActivity.INTENT_ICCID);
                    if (TextUtils.isEmpty(iccid)) {
                        return;
                    }
                    Intent intentPhone = new Intent();
                    intentPhone.putExtra(SELECT_SIM_NUM_KEY, iccid);
                    intentPhone.putExtra(SELECT_SIM_NUM_ID_KEY, iccid);
                    setResult(RESULT_OK, intentPhone);
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    private void connectNetErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mPullRecyclerView.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    private void normalLayout() {
        if (mPullRecyclerView.getVisibility() == View.GONE) {
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    RequestCallBack<String> CallBackUp = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                ChooseSimModel model = JSON.parseObject(result, ChooseSimModel.class);
                if (model != null) {
                    if (model.getStatus() == 1) {
                        List<ChooseSimModel.DataBean.ListBean> mListBeans = model.getData().getList();
                        if (mListBeans == null || mListBeans.size() == 0) {
                            if (mlisbean == null || mlisbean.size() == 0) {
                                noDataLayout();
                            } else {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                            return;
                        }
                        if (page == 1) {
                            mlisbean.clear();
                        }
                        normalLayout();
                        ChooseSimModel.DataBean.ListBean mlistbean;
                        for (ChooseSimModel.DataBean.ListBean lisbean : model.getData().getList()) {
                            mlistbean = new ChooseSimModel.DataBean.ListBean();
                            mlistbean.setIccid_no(lisbean.getIccid_no());
                            mlistbean.setIccid_no(lisbean.getIccid_no());
                            mlistbean.setAdd_time(lisbean.getAdd_time());
                            mlistbean.setBatch_name(lisbean.getBatch_name());
                            mlistbean.setId(lisbean.getId());
                            mlisbean.add(mlistbean);
                        }
                        mAdapter.notifyDataSetChanged();
                        // 当剩余还有大于0页的数据时，开启上拉加载更多
                        if(mListBeans.size() >= 10){
                            page++;
                            mPullRecyclerView.enableLoadMore(true);
                        }else {
                            mPullRecyclerView.enableLoadMore(false);
                        }
                    } else {
                        if (mlisbean == null || mlisbean.size() == 0) {
                            noDataLayout();
                        }
                        mPullRecyclerView.enableLoadMore(false);
                    }
                } else {
                    if (mlisbean == null || mlisbean.size() == 0) {
                        noDataLayout();
                    }
                    mPullRecyclerView.enableLoadMore(false);
                }
            } catch (Exception ex) {
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            if (mlisbean != null && mlisbean.size() > 0) {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            } else {
                connectNetErrorLayout();
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            try {
                mPullRecyclerView.stopRefresh();
                mPullRecyclerView.stopLoadMore();
            } catch (Exception ex) {
            }

        }
    };

}
